package com.android.music.prolyric;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;

public class AudioService extends Service implements OnCompletionListener {
	private ArrayList<HashMap<String, String>> songs;
	private int songIndex;
	private boolean isRepeat, isShuff;
	private MediaPlayer mp; 
	private AudioServiceBinder basBinder = new AudioServiceBinder();
	private Intent loadLyricInten ;
	private Intent broadcastIntentSongInfo = new Intent();
	private boolean playOnline = false ;
	private String[] onlineSongData;
	private IntentFilter songOnlineIf;
	public  int lyricID ;
	private String [] songinfors = new String [3];
	private boolean pauseSong = false;
	public static boolean online=false;
	private int check=0;
	
	private BroadcastReceiver playOnlineReciver = new  BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			playOnline = true;
			onlineSongData = intent.getExtras().getStringArray("dataonline");
			if(onlineSongData != null)
			{
				check=0;
				playSongOnline();
			}
			
		}
	};
	/*
	 * Khoi tao Binder
	 * */
	
	
	public class AudioServiceBinder extends Binder
	{
		public AudioService getService()
		{
			return AudioService.this;
		}
	}
	
	
	@Override
	public void onCreate() {
		
		// TODO Auto-generated method stub
		super.onCreate();
		lyricID = 0;
		Log.d("onCreate Service", "Khoi tao nhac, doc list tu file");
		loadLyricInten =  new Intent(this,LoadLyricService.class);
		mp = new MediaPlayer();
		mp.setOnCompletionListener(this);
		
		//Resgister for get SongOnline
		songOnlineIf = new IntentFilter();
		songOnlineIf.addAction("DATA_PLAY");
		registerReceiver(playOnlineReciver, songOnlineIf);
		
		//setAction for broadcast SongInfo;
		broadcastIntentSongInfo.setAction("GET_SONG_INFO");
		
		File currentStateFile = new File(getFilesDir()+"/"+"current_state.txt");
		if(currentStateFile.exists())
		{
			Log.d("doc file", "doc file thanh cong");
			try {
				FileInputStream fis = new FileInputStream(currentStateFile);
				DataInputStream dis = new DataInputStream(fis);
				songs = new ArrayList<HashMap<String, String>>();
				
				int size = dis.readInt();
				for(int i = 0 ; i<size; i++)
				{
					HashMap<String, String> h = new  HashMap<String, String>();
					h.put("songname", dis.readUTF());
					h.put("title", dis.readUTF());
					h.put("songpath", dis.readUTF());
					h.put("artist", dis.readUTF());
					songs.add(h);
					//songs.add(s);
				}
				songIndex = dis.readInt();
				isRepeat = dis.readBoolean();
				isShuff = dis.readBoolean();
				dis.close();
				fis.close();
			} catch (Exception e) {
				Log.d("Loi doc file", ""+e);
			}
			
			
		}
		else //nguoc lai neu day la lan dau tien vao ung dung, get toan bo bai hat co trong the nho
		{
			Cursor cursor;
			
			String[] columns = {
					MediaStore.Audio.Media.DATA,
					MediaStore.Audio.Media._ID,
					MediaStore.Audio.Media.TITLE,
					MediaStore.Audio.Media.DISPLAY_NAME,
					MediaStore.Audio.Media.MIME_TYPE,
					MediaStore.Audio.Media.ARTIST
					
					};
			
			
			//String whereVal[] = {cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM))};
			String orderBy = android.provider.MediaStore.Audio.Media.TITLE;
			cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,columns, null, null, orderBy);
			if(cursor==null)
			{
				Intent ErrorNoMusicIntent = new Intent();
				ErrorNoMusicIntent.setAction("ERROR_NO_MUSIC");
				getBaseContext().sendBroadcast(ErrorNoMusicIntent);
				stopSelf();
				
				
			}
			
			else 
			{
				if(cursor.moveToFirst())
				{
					songs = new ArrayList<HashMap<String,String>>();
					do{
						HashMap<String, String> s = new HashMap<String, String>();
						/*Song s = new Song();
						 * 
						s.setAudioFilePath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
						s.setSong_display_name(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
						s.setArtist(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));*/
						s.put("songname", cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
						s.put("songpath", cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
						s.put("title", cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
						s.put("artist", cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
						songs.add(s);
					}while (cursor.moveToNext());
				}
				
				
				songIndex = 0 ;
				isRepeat = false ;
				isShuff = false;
			}
			cursor.close();
		}
		//for(Song s : songs )
			
		
		
	}
	
	/*
	 * tra ve tong thoi gian va thoi gian hien tai cua mot bai hat
	 * hai thong so nay dung de updat progressbar; OK ?
	 * */
	public int gettotalDuration()
	{
		try {
			return mp.getDuration();
		} catch (Exception e) {
			return 0;
		}
			
		
			
	}
	
	public int getcurrentDuration()
	{
		try {
			return mp.getCurrentPosition();
		} catch (Exception e) {
			return 0;
		}
	}
	
	public void seekTo(int currentTime)
	{
		mp.seekTo(currentTime);
	}
	
	/*
	 * get state of mediaplayer
	 * */
	
	public boolean getStateMP()
	{
		return mp.isPlaying();
	}
	
	public boolean getRepeat()
	{
		return this.isRepeat;
	}
	
	public boolean getShuffe()
	{
		return isShuff;
	}
	
	public void setRepeat(boolean isRepeat)
	{
		this.isRepeat = isRepeat;
	}
	
	public void setShuffe(boolean isShuffe)
	{
		this.isShuff = isShuffe;
	}
	
	/*
	 * play song 
	 * 
	 * */

	/*
	 * Start service from GUI
	 * arg : String urlsong to search
	 * */
	
	public void startServiceFromGUI(Bundle bundle)
	{
		loadLyricInten.removeExtra("songname");
		loadLyricInten.removeExtra("singer");
		loadLyricInten.putExtras(bundle);
		startService(loadLyricInten);
	}
	
	public void playSong()
	{
		online=false;
		playOnline=false;
		if(!isRepeat)
		{
			//stopService(loadLyricInten);
			lyricID++;
			Log.d("playsong", "lyricID "+ lyricID);
			String songTitleFull = songs.get(songIndex).get("title");
			String songTitle = songs.get(songIndex).get("title");
			String singer = "";
			if(songTitleFull.lastIndexOf("-")>0)
				songTitle = songTitleFull.substring(0,songTitle.lastIndexOf("-")).trim();
			singer = songs.get(songIndex).get("artist");
			if(singer.indexOf("unknow")>0 && songTitleFull.indexOf("-")>0)
				singer = songTitleFull.substring(songTitleFull.indexOf("-")+1,songTitleFull.length()).trim();
			
				loadLyricInten.removeExtra("urlSong");
				loadLyricInten.putExtra("songname", songTitle);
				loadLyricInten.putExtra("lyricID", lyricID);
				loadLyricInten.putExtra("singer", singer);
				startService(loadLyricInten);
			
			//gui thong tin ve bai hat ve cho GUI thong qua broadcast
			
			songinfors[0] = songTitle;
			songinfors[1] = singer;
			songinfors[2] = (songIndex+1)+"/"+songs.size();
			
			
			Bundle b = new Bundle();
			b.putStringArray("songInfors", songinfors);
			b.putBoolean("setPauseSong", this.pauseSong);
			if(this.pauseSong)
			{
			
				this.pauseSong = false;
			}
			broadcastIntentSongInfo.putExtras(b);
			getBaseContext().sendBroadcast(broadcastIntentSongInfo);
		}
		
		try {
			mp.reset();
			mp.setDataSource(songs.get(songIndex).get("songpath"));
			mp.prepare();
			mp.start();
		} catch (Exception e) {
			Log.d("mediaplayerloi", "loi choi nhac "+e);
		}
	}
	
	
	
	public void playSongOnline()
	{
		//this.lyricID++;
		online=true;
		this.pauseSong = false;
		if(check==0)
		{
			songinfors[0] = onlineSongData[0];
			songinfors[1] = onlineSongData[1];
			songinfors[2] = "Play Song Online";
				
			Bundle b = new Bundle();
			b.putStringArray("songInfors", songinfors);
			broadcastIntentSongInfo.putExtras(b);
			getBaseContext().sendBroadcast(broadcastIntentSongInfo);
			
		
			loadLyricInten.putExtra("songname", onlineSongData[0]);
			loadLyricInten.putExtra("singer", onlineSongData[1]);
			loadLyricInten.putExtra("urlSong", onlineSongData[3]);
			
			startService(loadLyricInten);
		}		
		
		try {
			mp.reset();
			mp.setDataSource(onlineSongData[2]);
			mp.prepare();
			mp.start();
		} catch (Exception e) {
			Log.d("mediaplayerloi", "loi choi nhac "+e);
		}
	}
	
	
	public void pauseSong()
	{
		if(mp.isPlaying())
			mp.pause();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		
		//Unregister PlayOnline reciver;
		unregisterReceiver(playOnlineReciver);
		/*
		 * khi service ket thuc, tien hanh luu song,indexsong, isrepeat, isshuff vo file
		 * */
		
		if(songs != null)
		{
			Log.i("onDestroyService", ""+songs.size());
			File currentState = new File(getFilesDir(),"current_state.txt");
			
				try {
					FileOutputStream fos = new FileOutputStream(currentState);
					DataOutputStream dos = new DataOutputStream(fos);
					dos.writeInt(songs.size());
					for(int i = 0 ; i< songs.size(); i++)
					{
						dos.writeUTF(songs.get(i).get("songname"));
						dos.writeUTF(songs.get(i).get("title"));
						dos.writeUTF(songs.get(i).get("songpath"));
						dos.writeUTF(songs.get(i).get("artist"));
					}
					dos.writeInt(songIndex);
					dos.writeBoolean(isRepeat);
					dos.writeBoolean(isShuff);
					dos.flush();
					dos.close();
					fos.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
		
		}
		Log.d("OnDestroy Service", "tat nhac");
		mp.release();
	}
	
	
	/*switch play/pause*/
	
	public boolean switchPlayPause()
	{
		if(mp.isPlaying())
		{
			mp.pause();
			return true;
		}
		else 
		{
			mp.start();
			return false;
		}
	}
	
	
	/*
	 * Xu li button Next;
	 * */
	
	public void NextSong()
	{
		
		//stopService(loadLyricInten);
		
		Log.i("stopService", "ok");
		
		

			
			if(songIndex == (songs.size() - 1)){
				
				songIndex = 0;
				playSong();
			}else{
				// play first song
				songIndex++;
				playSong();
				
			}
		
		
	}
	
	/*
	 * xu li button Previous
	 * */
	
	public void PreviousSong()
	{
		
		Log.i("stopService", "ok");
		
		//stopService(loadLyricInten);
		if(songIndex > 0){
			songIndex = songIndex - 1;
			playSong();
			
		}else{
			// play last song
			
			songIndex = songs.size() - 1;
			playSong();
		}
	}

	/*cho nay quan trong nhat*/
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		Log.d("start command", "bat dau choi nhac startId = "+ startId + "Intent = " + intent +" "+flags);
		Log.d("songIndex", " " +songIndex);
		int type_start = intent.getExtras().getInt("type_start");
		Log.d("type_start", ""+type_start);
		
		//lyricID = 0;
		if(type_start == 0 )
		{  
			
			try {
				String songTitleFull = songs.get(songIndex).get("title");
				String songTitle = songs.get(songIndex).get("title");
				String singer = "";
				if(songTitleFull.lastIndexOf("-")>0)
					songTitle = songTitleFull.substring(0,songTitle.lastIndexOf("-")).trim();
				singer = songs.get(songIndex).get("artist");
				if(singer.indexOf("unknow")>0 && songTitleFull.indexOf("-")>0)
					singer = songTitleFull.substring(songTitleFull.indexOf("-")+1,songTitleFull.length()).trim();
				if(songinfors[0] == null)
				{
					songinfors[0] = songTitle;
					songinfors[1] = singer;
					songinfors[2] = (songIndex+1)+"/"+songs.size();
				}
				Bundle b = new Bundle();
				b.putStringArray("songInfors", songinfors);
				broadcastIntentSongInfo.putExtras(b);
				
				
				
				 
				if(!mp.isPlaying())
				{
					Log.d("startCommand", "lan dau choi nhac, load nhac tu file");
					/*for(Song s: songs)
						Log.d("startCommand", s.getAudioFilePath());*/
					/*try {
						mp.reset();
						Log.d("get tai Song index", songs.get(songIndex).getAudioFilePath());
						mp.setDataSource(songs.get(songIndex).getAudioFilePath());
						mp.prepare();
						mp.start();
					} catch (Exception e) {
						// TODO: handle exception
					}*/
					getBaseContext().sendBroadcast(broadcastIntentSongInfo);
					this.pauseSong = true;
					playSong();					
					this.pauseSong();
					
				}
				else 
				{
					this.pauseSong = false;
					b.putStringArray("songInfors", songinfors);
					b.putBoolean("setPauseSong", this.pauseSong);
					broadcastIntentSongInfo.putExtras(b);
					
					
					getBaseContext().sendBroadcast(broadcastIntentSongInfo);
					
					
					loadLyricInten.removeExtra("urlSong");
					loadLyricInten.putExtra("songname", songinfors[0]);
					loadLyricInten.putExtra("lyricID", lyricID);
					loadLyricInten.putExtra("singer", songinfors[1]);
					startService(loadLyricInten);
				}
			} catch (Exception e) {
				Intent ErrorNoMusicIntent = new Intent();
				ErrorNoMusicIntent.setAction("ERROR_NO_MUSIC");
				getBaseContext().sendBroadcast(ErrorNoMusicIntent);
				stopSelf();
			}
			
			
			
		}

		else if(type_start == 	1)
		{
			GlobalState global = (GlobalState)getApplicationContext();
			ArrayList<HashMap<String, String>> globalSongs = global.getGlobalSongs();
			if(globalSongs == null || globalSongs.isEmpty())
			{
				playSong();
			}
			
			else 
			{
				songs = globalSongs;
				songIndex = global.getSongIndex();
				playSong();
			}
		}
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.d("OnBind Service", "Khoi tao ket noi");
		return basBinder;
	}

	
	/*
	 * On Song complited
	 * */


	public void onCompletion(MediaPlayer arg0) {
		
		if(playOnline)
		{
			check++;
			playSongOnline();
		}
		else 
		{

			// check for repeat is ON or OFF
					if(isRepeat){
						// repeat is on play same song again
						playSong();
					} else if(isShuff){
						// shuffle is on - play a random song
						Random rand = new Random();
						songIndex = rand.nextInt((songs.size() - 1) - 0 + 1) + 0;
						playSong();
					} else{
						// no repeat or shuffle ON - play next song
						
						if(songIndex < (songs.size() - 1)){
							songIndex = songIndex + 1;
							playSong();
							
						}else{
							// play first song
							songIndex = 0;
							playSong();
						
						}
					}
			
		
		}
	}

}
